package com.engine.aviator.funs;

import com.googlecode.aviator.runtime.function.AbstractVariadicFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorDouble;
import com.googlecode.aviator.runtime.type.AviatorObject;

import java.util.Map;

public class AvgFunction  extends AbstractVariadicFunction {

    @Override
    public AviatorObject variadicCall(Map<String, Object> env, AviatorObject... args) {
        Double sum = 0D;
        Integer count = 0;
        for(AviatorObject arg:args){
            Number number = FunctionUtils.getNumberValue(arg, env);
            sum+=number.doubleValue();
            count++;
        }
        return new AviatorDouble(sum / count);
    }

    @Override
    public String getName() {
        return "udfAvg";
    }
}
